'use strict';

/* Controllers */

var fulboControllers = angular.module('fulboControllers', []);

fulboControllers.controller('BaseController', ['$rootScope', '$scope', '$location', 'UsersAuth', 
  function($rootScope, $scope, $location, UsersAuth) {
	$scope.logout = function() {
    	UsersAuth.logout();
    };
    $scope.login = function() {
    	UsersAuth.login();
    };
    $scope.openGroupsView = function() {
    	$location.path( "/groups" );
    };
    $scope.openMatchesView = function() {
    	$location.path( "/matches" );
    };
    $scope.openProfileView = function() {
    	$location.path( "/profile" );
    };
    $scope.openHomeView = function() {
    	$location.path( "/" );
    };
}]);

fulboControllers.controller('HomeController', ['$rootScope', '$scope', '$location', 'Fields', 'Matches', 'UsersAuth',
  function($rootScope, $scope, $location, Fields, Matches, UsersAuth) {
    $rootScope.activePage = "home";
	
    $scope.matchToSave = false;
    
    $scope.login = function() {
    	UsersAuth.login();
    };
    
    $scope.openNewFieldModal = function() {
    	$('#newFieldModal').modal('show');
    };
    
    $scope.newField = function() {
    	var name = $("#newFieldName").val();
    	var address = $("#newFieldAddress").val();
    	var town = $("#newFieldTown").val();
    	var state = $("#newFieldState").val();
    	
    	if(name == ""){
    		showAlert("Error", "Debe ingresar el nombre de la cancha.");
    		return false;
    	}
    	if(address == ""){
    		showAlert("Error", "Debe ingresar la dirección de la cancha.");
    		return false;
    	}
    	
		var field = {
	        name: name,
	        address: address,
	        town: town,
	        state: state
		};
	    	
		Fields.save(field, function(newField){
	    	console.log("Field saved, id:" + newField.id);
	    	$rootScope.fields = Fields.query();
	    }, function(){
	    	console.log("Failed saving field!");
	    	showAlert("Error", "Hubo un error al crear la cancha! Intente nuevamente.");
	    });
		
    	$('#newFieldModal').modal('hide');
    };
    
    $scope.createMatch = function(){
    	var date = moment($("#matchDate").val(), "DD/MM/YYYY").format('YYYY-MM-DD');
	    var dateTime = date + " " + $("#matchHour").val();
	    var fieldId = $("#matchField").val();
	    var matchTypeId = $("#matchType").val();
	    var admin_userId = $rootScope.user.id;
	    
	    if(date == "Invalid date") {
	    	showAlert("Error", "Debe elegir una fecha válida para el partido.");
	    	return false;
	    }
	    if(dateTime == "Invalid date") {
	    	showAlert("Error", "Debe elegir una hora válida para el partido.");
	    	return false;
	    }
	    if(fieldId == null) {
	    	showAlert("Error", "Debe elegir una sede para el partido.");
	    	return false;
	    }
	    if(matchTypeId == null) {
	    	showAlert("Error", "Debe elegir la cantidad de jugadores.");
	    	return false;
	    }

	    var match = {
	    	date: dateTime,
	    	fieldId: fieldId,
	    	comments: "",
	        cancelled: 0,
	    	matchTypeId: matchTypeId,
	    	admin_userId: admin_userId
	    };
	    
	    Matches.save(match, function(newMatch){
	    	console.log("Match saved, id:" + newMatch.id);
	    	$location.path( "match/" + newMatch.id );
	    }, function(){
	    	console.log("Failed saving match!");
	    	showAlert("Error", "Hubo un error al crear el partido! Intente nuevamente.");
	    });
    };

    $scope.tryCreateMatch = function(){
    	if(UsersAuth.isLogged){
    		$scope.createMatch();
    	} else {
    		$('#registerModal').modal('show');
    	}
    };
  }]);

fulboControllers.controller('MatchesController', ['$rootScope', '$scope', '$location', 'Users', 'Matches', 'Teams', 'Facebook',   
	function($rootScope, $scope, $location, Users, Matches, Teams, Facebook) {
		$rootScope.activePage = "matches";
		
		//TODO: filtrar por guest si/guest no/admin!
		$scope.matches = Users.getMatches({id: $rootScope.user.id});
		$scope.openMatch = function(matchId){
			$location.path( "match/" + matchId );
		};
		
		$scope.answerYes = function(match){
	    	var teamAUpdated = false;
	    	var teamBUpdated = false;
	    	var subsUpdated = false;
	    	
	    	//mark as confirmed
	    	var data = {
		    	users: [],
		    	matchId: match.id
		    };
	    	for(var i = 0; i < match.guests.length; i++){
	    		var confirmed = match.guests[i].pivot.confirmed;
	    		if(match.guests[i].id == $rootScope.user.id)
	    			confirmed = 1;
	    		var userItem = {
	    			id: match.guests[i].fbId != null? match.guests[i].fbId.toString() : match.guests[i].id.toString(),
	    			confirmed: confirmed
	    		};
	    		data.users.push(userItem);
	    	}
	    	Matches.updateGuests(data, function(response){
	    		//add player to team or subs
		    	var dataSubs = {
		    	    userIds: [],
		    	    matchId: match.id
		    	};
		    	var dataTeamA = {
		    	    userIds: [],
		    	    teamId: match.teams[0].id
		    	};
		    	var dataTeamB = null;
		    	if(match.teams.length > 1)
			    	dataTeamB = {
			    	   	userIds: [],
			    	   	teamId: match.teams[1].id
			    	};
		    	
		    	var teamAMissingPlayers = match.type.totalPlayers / 2 - match.teams[0].users.length;
		    	var teamBMissingPlayers = dataTeamB != null ? (match.type.totalPlayers / 2 - match.teams[1].users.length) : 0;
		    	if(teamAMissingPlayers > 0 && teamBMissingPlayers > teamAMissingPlayers && dataTeamB != null){ //add to teamB
		    		dataTeamB.userIds.push($rootScope.user.fbId);
		    		teamBUpdated = true;
		    	} else if(teamAMissingPlayers > 0){ //add to teamA
		    		dataTeamA.userIds.push($rootScope.user.fbId);
		    		teamAUpdated = true;
		    	} else { //add to subs
		    		dataSubs.userIds.push($rootScope.user.fbId);
		    		subsUpdated = true;
		    	}
		    	
		    	if(teamAUpdated)
			   		$scope.updateTeam(dataTeamA, match.teams[0]);
			   	if(teamBUpdated)
			   		$scope.updateTeam(dataTeamB, match.teams[1]);
			   	if(subsUpdated)
			   		$scope.updateSubs(dataSubs, match.substitutes);
			   	
			   	var message = "Juego el partido del día " + match.date + " en " + match.field.name;
	    		var link = "http://www.futzapp.com?token=" + match.token;
	    		var actions = null;
	    		var tags = [match.admin.fbId];
	    		/*Facebook.getPlaceIdByLatLong(match.field.town, match.field.latitude, match.field.longitude, function(placeId){
	    			if(placeId != -1){*/
		    			Facebook.postNotification(message, link, tags, actions, function(){
		    				showAlert("Notificación", "Se ha enviado una notificación!");
						}, function(){
							showAlert("Error", "No se pudo enviar la notificación. Avisale al admin!");
						});
	    		/*	} else {
	    				showAlert("Error", "No se pudo enviar la notificación. Avisale al admin!");
	    			}
	    		});*/
			   	
			   	$scope.matches = Users.getMatches({id: $rootScope.user.id});
	    	});
	    };
	    
	    $scope.answerNo = function(match){
	    	//mark as rejected
	    	var data = {
			   	users: [],
			   	matchId: match.id
			};
		    for(var i = 0; i < match.guests.length; i++){
		    	var confirmed = match.guests[i].pivot.confirmed;
		    	if(match.guests[i].id == $rootScope.user.id)
		    		confirmed = 0;
		    	var userItem = {
		    		id: match.guests[i].fbId != null? match.guests[i].fbId.toString() : match.guests[i].id.toString(),
		    		confirmed: confirmed
		    	};
		    	data.users.push(userItem);
		    }
		    Matches.updateGuests(data, function(response){
		    	//remove player from team or subs
		    	var dataSubs = {
		    		userIds: [],
			    	matchId: match.id
			    };
			    var dataTeamA = {
			        userIds: [],
			        teamId: match.teams[0].id
			    };
			    var dataTeamB = null;
		    	if(match.teams.length > 1)
			    	dataTeamB = {
			    	   	userIds: [],
			    	   	teamId: match.teams[1].id
			    	};
		    	
			   	$scope.updateTeam(dataTeamA, match.teams[0], $rootScope.user.id);
			   	if(dataTeamB != null)
			   		$scope.updateTeam(dataTeamB, match.teams[1], $rootScope.user.id);
			   	$scope.updateSubs(dataSubs, match.substitutes, $rootScope.user.id);
			   	
			   	var message = "No juego el partido del día " + match.date + " en " + match.field.name;
	    		var link = "http://www.futzapp.com?token=" + match.token;
	    		var actions = null;
	    		var tags = [match.admin.fbId];
	    		/*Facebook.getPlaceIdByLatLong(match.field.town, match.field.latitude, match.field.longitude, function(placeId){
	    			if(placeId != -1){*/
		    			Facebook.postNotification(message, link, tags, actions, function(){
		    				showAlert("Notificación", "Se ha enviado una notificación!");
						}, function(){
							showAlert("Error", "No se pudo enviar la notificación. Avisale al admin!");
						});
	    		/*	} else {
	    				showAlert("Error", "No se pudo enviar la notificación. Avisale al admin!");
	    			}
	    		});*/
			   	
			   	$scope.matches = Users.getMatches({id: $rootScope.user.id});
		    });
	    };
	    
	    $scope.updateSubs = function(data, subs, toRemoveUserId){
	    	var update = toRemoveUserId == undefined ? true : false;
	    	//add existing subs
	    	for(var i = 0; i < subs.length; i++){
	    		if(toRemoveUserId != undefined && subs[i].id == toRemoveUserId){
	    			update = true;
	    			continue;
	    		}
	    		data.userIds.push(subs[i].fbId.toString());
	    	}
	    	if(update)
		   		Matches.updateSubs(data, function(response){
		   			/*if(toRemoveUserId != undefined) showAlert("Alerta", "Te diste de baja del partido!");
		   			else showAlert("Alerta", "Te anotaste como suplente para el partido!");*/
		    	});
	    };
	    $scope.updateTeam = function(data, team, toRemoveUserId){
	    	var update = toRemoveUserId == undefined ? true : false;
	    	//add existing players
	    	for(var i = 0; i < team.users.length; i++){
	    		if(toRemoveUserId != undefined && team.users[i].id == toRemoveUserId){
	    			update = true;
	    			continue;
	    		}
	    		var id = team.users[i].fbId != undefined ? team.users[i].fbId.toString() : team.users[i].id.toString();
	    		data.userIds.push(id);
	    	}
	    	if(update)
		   		Teams.updateUsers(data, function(response){
		   			/*if(toRemoveUserId != undefined) showAlert("Alerta", "Te diste de baja del partido!");
		   			else showAlert("Alerta", "Te anotaste como titular para el partido!");*/
		    	});
	    };
}]);

fulboControllers.controller('MatchController', ['$rootScope', '$scope', '$routeParams', '$location', 'Matches', 'Teams', 'Users', 'Facebook', 
    function($rootScope, $scope, $routeParams, $location, Matches, Teams, Users, Facebook) {
		$rootScope.activePage = "matches";
		$scope.currentURL = $location.host();
		
		$scope.totalPlayers = 0;
		$scope.friendsSelected = [];
		$scope.modoVersus = false;
		
		$scope.groups = Users.getGroups({id: $rootScope.user.id});
		Facebook.getFriends(function(response) {
			$scope.friends = response;
		});
		
	    $scope.getNumber = function(num) {
		    return new Array(num);   
		};
		
		$scope.teamA = {
				team: null,
				positions: [],
				missingPlayers: 0
		};
		$scope.teamB = {
				team: null,
				positions: [],
				missingPlayers: 0
		};
		$scope.tooltipA = false;
		$scope.showTeamAColors = false;
		$scope.showTeamBColors = false;
		$scope.setTeamAColor = function(color){
			$scope.teamA.team.shirtColor = color;
			Teams.update($scope.teamA.team, function(response){
				$scope.teamA.team = response;
    		});
		};
		$scope.setTeamBColor = function(color){
			$scope.teamB.team.shirtColor = color;
			Teams.update($scope.teamB.team, function(response){
				$scope.teamB.team = response;
    		});
		};
		
		$scope.renderMatch = function(){
			return Matches.get({id: $routeParams.matchId}, function(){
				var teams = Matches.getTeams({id: $routeParams.matchId}, function(){
					if(teams.length == 1)
						$scope.modoVersus = true;
					if(!$scope.modoVersus) $scope.totalPlayers = $scope.match.type.totalPlayers / 2;
					else $scope.totalPlayers = $scope.match.type.totalPlayers;
					var positions = $scope.match.type.formation.split(";");
					
					if(teams.length == 0) {
						$scope.teamA.missingPlayers = $scope.totalPlayers;
						$scope.teamB.missingPlayers = $scope.totalPlayers;
					}
					if(teams.length > 0) {
						$scope.teamA.team = teams[0];
						$scope.teamA.missingPlayers = $scope.totalPlayers - teams[0].users.length;
						
						//map positions
						for(var i = 0; i < $scope.totalPlayers; i++){
							var xy = positions[i].split(",");
							var position = {
									x: xy[0] + "px",
									y: xy[1] + "px"
							};
							$scope.teamA.positions.push(position);
						}
					}
					if(teams.length > 1) {
						$scope.teamB.team = teams[1];
						$scope.teamB.missingPlayers = $scope.totalPlayers - teams[1].users.length;
						
						//map positions
						for(var i = 5; i <  $scope.totalPlayers * 2; i++){
							var xy = positions[i].split(",");
							var position = {
									x: xy[0] + "px",
									y: xy[1] + "px"
							};
							$scope.teamB.positions.push(position);
						}
					}
				});
				
				//field map
				var fieldPos = new google.maps.LatLng($scope.match.field.latitude, $scope.match.field.longitude);
				var mapOptions = {
					center: fieldPos,
					zoom: 14,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				};
				var map = new google.maps.Map(document.getElementById("map_canvas"),
								mapOptions); 
				var marker = new google.maps.Marker({
					position: fieldPos,
					map: map,
					title: '$scope.match.field.name'
				});
			});	
		};
		
		$scope.match = $scope.renderMatch();
		$scope.subs = Matches.getSubs({id: $routeParams.matchId});
		
		$scope.userConfirmed = null;
		$scope.guests = Matches.getGuests({id: $routeParams.matchId}, function(){
			for(var i = 0; i < $scope.guests.length; i++){
				if($scope.guests[i].id == $rootScope.user.id){
					$scope.userConfirmed = $scope.guests[i].pivot.confirmed;
					break;
				}
			}
		});
		
		
		
		$scope.selectGroup = function(group){
			if(group.selected == undefined || !group.selected){
				group.selected = true;
				for(var i = 0; i < group.users.length; i++){
					if(group.users[i].id == $rootScope.user.id)
						continue;
					
					var friend = {
							id: group.users[i].fbId,
							name: group.users[i].name + " " + group.users[i].lastName
					};
					$scope.friendsSelected.push(friend);
				}
			} else {
				group.selected = false;
				for(var j = 0; j < group.users.length; j++){
					for(var i = 0; i < $scope.friendsSelected.length; i++) {
		                if($scope.friendsSelected[i].id === group.users[j].fbId) {
		                	$scope.friendsSelected.splice(i, 1);
		                	break;
		                }
		            }
				}
			}
		};
		
		$scope.selectFriend = function(friend){
			if(friend.selected == undefined || !friend.selected){
				friend.selected = true;
				$scope.friendsSelected.push(friend);
			} else {
				friend.selected = false;
				for(var i = 0; i < $scope.friendsSelected.length; i++) {
	                if($scope.friendsSelected[i].name === friend.name) {
	                	$scope.friendsSelected.splice(i, 1);
	                	break;
	                }
	            }
			}
		};
		
		$scope.isSelected = function(obj) {
	        return obj.selected;
	    };
	    
	    $scope.cancelMatch = function(){
	    	$('#editMatchModal').modal('hide');
    		$scope.match.cancelled = 1;
	    	Matches.update($scope.match, function(){
	    		var message = "Cancelamos el partido del día " + $scope.match.date + " en " + $scope.match.field.name;
	    		var link = "http://www.futzapp.com";
	    		var actions = null;
	    		var tags = [];
	    		for(var i = 0; i < $scope.guests.length; i++) {
	                if($scope.guests[i].pivot.confirmed == "1" && $scope.guests[i].id != $rootScope.user.id && $scope.guests[i].fbId != null) {
	                	tags.push($scope.guests[i].fbId);
	                }
	            }
	    		tags = tags.join(',');
	    		/*Facebook.getPlaceIdByLatLong($scope.match.field.town, $scope.match.field.latitude, $scope.match.field.longitude, function(placeId){
	    			if(placeId != -1){*/
		    			Facebook.postNotification(message, link, tags, actions, function(){
		    				showAlert("Notitificación", "Se ha enviado una notificación!");
						}, function(){
							showAlert("Error", "No se pudo enviar la notificación. Avisale a tus amigos!");
						});
	    		/*	} else {
	    				showAlert("Error", "No se pudo enviar la notificación. Avisale a tus amigos!");
	    			}
	    		});*/
	    	});
	    };
	    
	    $scope.updateMatch = function(){
	    	$('#editMatchModal').modal('hide');
	    	var date = moment($("#matchEditDate").val(), "DD/MM/YYYY").format('YYYY-MM-DD');
		    var dateTime = date + " " + $("#matchEditHour").val();
		    $scope.match.date = dateTime;
    		Matches.update($scope.match, function(response){
    			$scope.match = $scope.renderMatch();
    		});
	    };
	    
	    $scope.invitePlayers = function() {
	    	var data = {
	    		users: [],
			    matchId: $scope.match.id
			};
	    	
	    	//add existing guests
	    	for(var i = 0; i < $scope.guests.length; i++){
	    		var userItem = {
		    		id: $scope.guests[i].fbId != null? $scope.guests[i].fbId.toString() : $scope.guests[i].id.toString(),
		    		confirmed: $scope.guests[i].pivot.confirmed
		    	};
	    		data.users.push(userItem);
	    	}
	    	
	    	//add new members
	    	for(var i = 0; i < $scope.friendsSelected.length; i++){
	    		var userItem = {
			    	id: $scope.friendsSelected[i].id.toString(),
			    	confirmed: null
			    };
		    	data.users.push(userItem);
	    	}
	    	
	    	var message = "Copate a un fulbo el " + $scope.match.date + " en " + $scope.match.field.name;
    		var link = "http://www.futzapp.com";
    		var actions = null;
    		var tags = [];
    		for(var i = 0; i < $scope.friendsSelected.length; i++) {
                tags.push($scope.friendsSelected[i].id);
            }
    		tags = tags.join(',');
    		/*Facebook.getPlaceIdByLatLong($scope.match.field.town, $scope.match.field.latitude, $scope.match.field.longitude, function(placeId){
    			if(placeId != -1){*/
	    			Facebook.postNotification(message, link, tags, actions, function(){
	    				showAlert("Notificación", "Se ha enviado una notificación!");
					}, function(){
						showAlert("Error", "No se pudo enviar la notificación. Avisale a tus amigos!");
					});
    		/*	} else {
    				showAlert("Error", "No se pudo enviar la notificación. Avisale a tus amigos!");
    			}
    		});*/
    		
	    	Matches.updateGuests(data, function(response){
	    		$('#invitePlayersModal').modal('hide');
	    	});
	    };
	    
	    $scope.answerYes = function(){
	    	var teamAUpdated = false;
	    	var teamBUpdated = false;
	    	var subsUpdated = false;
	    	
	    	//mark as confirmed
	    	var data = {
		    	users: [],
		    	matchId: $scope.match.id
		    };
	    	for(var i = 0; i < $scope.guests.length; i++){
	    		var confirmed = $scope.guests[i].pivot.confirmed;
	    		if($scope.guests[i].id == $rootScope.user.id)
	    			confirmed = 1;
	    		var userItem = {
	    			id: $scope.guests[i].fbId != null? $scope.guests[i].fbId.toString() : $scope.guests[i].id.toString(),
	    			confirmed: confirmed
	    		};
	    		data.users.push(userItem);
	    	}
	    	Matches.updateGuests(data, function(response){
	    		//add player to team or subs
		    	var dataSubs = {
		    	    userIds: [],
		    	    matchId: $scope.match.id
		    	};
		    	var dataTeamA = {
		    	    userIds: [],
		    	    teamId: $scope.teamA.team.id
		    	};
		    	var dataTeamB = null;
		    	if($scope.teamB.team != null)
			    	dataTeamB = {
			    	   	userIds: [],
			    	   	teamId: $scope.teamB.team.id
			    	};
		    	
		    	if($scope.teamA.missingPlayers > 0 && $scope.teamB.missingPlayers > $scope.teamA.missingPlayers && dataTeamB != null){ //add to teamB
		    		dataTeamB.userIds.push($rootScope.user.fbId);
		    		teamBUpdated = true;
		    	} else if($scope.teamA.missingPlayers > 0){ //add to teamA
		    		dataTeamA.userIds.push($rootScope.user.fbId);
		    		teamAUpdated = true;
		    	} else { //add to subs
		    		dataSubs.userIds.push($rootScope.user.fbId);
		    		subsUpdated = true;
		    	}
		    	
		    	if(teamAUpdated)
			   		$scope.updateTeamA(dataTeamA);
			   	if(teamBUpdated)
			   		$scope.updateTeamB(dataTeamB);
			   	if(subsUpdated)
			   		$scope.updateSubs(dataSubs);
		    	
		    	$scope.userConfirmed = 1;
		    	
		    	var message = "Juego el partido del día " + $scope.match.date + " en " + $scope.match.field.name;
	    		var link = "http://www.futzapp.com";
	    		var actions = null;
	    		var tags = $scope.match.admin.fbId;
	    		/*Facebook.getPlaceIdByLatLong($scope.match.field.town, $scope.match.field.latitude, $scope.match.field.longitude, function(placeId){
	    			if(placeId != -1){*/
		    			Facebook.postNotification(message, link, tags, actions, function(){
		    				showAlert("Notificación", "Se ha enviado una notificación!");
						}, function(){
							showAlert("Error", "No se pudo enviar la notificación. Avisale al admin!");
						});
	    		/*	} else {
	    				showAlert("Error", "No se pudo enviar la notificación. Avisale al admin!");
	    			}
	    		});*/
	    	});
	    };
	    
	    $scope.answerNo = function(){
	    	//mark as rejected
	    	var data = {
			   	users: [],
			   	matchId: $scope.match.id
			};
		    for(var i = 0; i < $scope.guests.length; i++){
		    	var confirmed = $scope.guests[i].pivot.confirmed;
		    	if($scope.guests[i].id == $rootScope.user.id)
		    		confirmed = 0;
		    	var userItem = {
		    		id: $scope.guests[i].fbId != null? $scope.guests[i].fbId.toString() : $scope.guests[i].id.toString(),
		    		confirmed: confirmed
		    	};
		    	data.users.push(userItem);
		    }
		    Matches.updateGuests(data, function(response){
		    	//remove player from team or subs
		    	var dataSubs = {
		    		userIds: [],
			    	matchId: $scope.match.id
			    };
			    var dataTeamA = {
			        userIds: [],
			        teamId: $scope.teamA.team.id
			    };
			    var dataTeamB = null;
		    	if($scope.teamB.team != null)
			    	dataTeamB = {
			    	   	userIds: [],
			    	   	teamId: $scope.teamB.team.id
			    	};
			   	$scope.updateTeamA(dataTeamA, $rootScope.user.id);
			   	if(dataTeamB != null)
			   		$scope.updateTeamB(dataTeamB,  $rootScope.user.id);
			   	$scope.updateSubs(dataSubs,  $rootScope.user.id);
			   	
			   	$scope.userConfirmed = 0;
			   	
			   	var message = "No juego el partido del día " + $scope.match.date + " en " + $scope.match.field.name;
	    		var link = "http://www.futzapp.com";
	    		var actions = null;
	    		var tags = $scope.match.admin.fbId;
	    		/*Facebook.getPlaceIdByLatLong($scope.match.field.town, $scope.match.field.latitude, $scope.match.field.longitude, function(placeId){
	    			if(placeId != -1){*/
		    			Facebook.postNotification(message, link, tags, actions, function(){
		    				showAlert("Notificación", "Se ha enviado una notificación!");
						}, function(){
							showAlert("Error", "No se pudo enviar la notificación. Avisale al admin!");
						});
	    		/*	} else {
	    				showAlert("Error", "No se pudo enviar la notificación. Avisale al admin!");
	    			}
	    		});*/
		    });
	    };
	    
	    $scope.selectedTeam = "A";
	    $scope.changeSelectedTeam = function(team){
	    	$scope.selectedTeam = team;
	    };
	    $scope.addPlayer = function(){
	    	var playerName = $("#newPlayerName").val();
	    	if(playerName == "" || playerName == undefined){
	    		showAlert("Error", "Tenés que poner el nombre de tu amigo!");
	    	} else {
	    		//crear usuario con solo nombre
	    		var user = {
	    			"name": playerName	
	    		};
	    		Users.save(user, function(response){
	    			//agregar usuario como invitado
	    			var data = {
	    		   		users: [],
	    			    matchId: $scope.match.id
	    			};
	    		    //add existing guests
	    		    for(var i = 0; i < $scope.guests.length; i++){
	    		    	var userItem = {
	    			   		id: $scope.guests[i].fbId != null? $scope.guests[i].fbId.toString() : $scope.guests[i].id.toString(),
	    			   		confirmed: $scope.guests[i].pivot.confirmed
	    			   	};
	    		    	data.users.push(userItem);
	    		    }
	    		    var userItem = {
	    			   	id: response.id,
	    			   	confirmed: 1
	    			};
	    			data.users.push(userItem);
	    			Matches.updateGuests(data, function(teamGuests){
	    				//agregar usuario al equipo elegido
		    			if($scope.selectedTeam == "A"){
		    				var dataTeamA = {
		    					userIds: [],
		    	    		    teamId: $scope.teamA.team.id
		    	    		};
		    				dataTeamA.userIds.push(response.id);
		    	    		$scope.updateTeamA(dataTeamA);
		    			}
		    			if($scope.selectedTeam == "B"){
		    				var dataTeamB = {
			    				userIds: [],
			    	    		teamId: $scope.teamB.team.id
			    	    	};
		    				dataTeamB.userIds.push(response.id);
			    	    	$scope.updateTeamB(dataTeamB);
		    			}
		    			$('#addPlayerModal').modal('hide');
	    	    	});
	    		});
	    	}
	    };
	    
	    $scope.updateSubs = function(data, toRemoveUserId){
	    	var update = toRemoveUserId == undefined ? true : false;
	    	//add existing subs
	    	for(var i = 0; i < $scope.subs.length; i++){
	    		if(toRemoveUserId != undefined && $scope.subs[i].id == toRemoveUserId){
	    			update = true;
	    			continue;
	    		}
	    		data.userIds.push($scope.subs[i].fbId.toString());
	    	}
	    	if(update)
		   		Matches.updateSubs(data, function(response){
		   			$scope.subs = response;
		   			/*if(toRemoveUserId != undefined) showAlert("Alerta", "Te diste de baja del partido!");
		   			else showAlert("Alerta", "Te anotaste como suplente para el partido!");*/
		    	});
	    };
	    $scope.updateTeamA = function(data, toRemoveUserId){
	    	var update = toRemoveUserId == undefined ? true : false;
	    	//add existing players
	    	for(var i = 0; i < $scope.teamA.team.users.length; i++){
	    		if(toRemoveUserId != undefined && $scope.teamA.team.users[i].id == toRemoveUserId){
	    			update = true;
	    			continue;
	    		}
	    		var id = $scope.teamA.team.users[i].fbId != undefined ? $scope.teamA.team.users[i].fbId.toString() : $scope.teamA.team.users[i].id.toString(); 
	    		data.userIds.push(id);
	    	}
	    	if(update)
		   		Teams.updateUsers(data, function(response){
		   			$scope.teamA.team = response;
					$scope.teamA.missingPlayers = $scope.totalPlayers - response.users.length;
		   			/*if(toRemoveUserId != undefined) showAlert("Alerta", "Te diste de baja del partido!");
		   			else showAlert("Alerta", "Te anotaste como titular para el partido!");*/
		    	});
	    };
	    $scope.updateTeamB = function(data, toRemoveUserId){
	    	var update = toRemoveUserId == undefined ? true : false;
	    	//add existing players
	    	for(var i = 0; i < $scope.teamB.team.users.length; i++){
	    		if(toRemoveUserId != undefined && $scope.teamB.team.users[i].id == toRemoveUserId){
	    			update = true;
	    			continue;
	    		}
	    		var id = $scope.teamB.team.users[i].fbId != undefined ? $scope.teamB.team.users[i].fbId.toString() : $scope.teamB.team.users[i].id.toString();
	    		data.userIds.push(id);
	    	}
	    	if(update)
		   		Teams.updateUsers(data, function(response){
		   			$scope.teamB.team = response;
					$scope.teamB.missingPlayers = $scope.totalPlayers - response.users.length;
					/*if(toRemoveUserId != undefined) showAlert("Alerta", "Te diste de baja del partido!");
		   			else showAlert("Alerta", "Te anotaste como titular para el partido!");*/
		    	});
	    };
	    
	    //match Share
	    $scope.shareFB = function(){
	    	//TODO: cambiar metodo feed (deprecated) por share_open_graph con story
	    	var url = "http://www.futzapp.com?token=" + $scope.match.token;
	    	//var url = "http://www.futzapp.com/back/public/matchSharer.php";
			/*FB.ui({
	    		method: 'share_open_graph',
	    		action_type: 'futzapp_test:jugar',
	    		action_properties: JSON.stringify({
	    			ref: $scope.match.token,
	    			start_time: $scope.match.date,
	    			fulbo: url
	    		})
	    	}, function(response){});
			FB.ui({
	    		method: 'share',
	    		href: url 
	    	}, function(response){});*/
			FB.ui( {
				method: 'feed',
				name: "Futzapp",
				link: url,
				picture: "http://futzapp.com/images/field.jpg",
				description: "Juguemos un fulbo el " + $scope.match.date + " en " + $scope.match.field.name,
				caption: "Ya reservaste cancha y te faltan jugadores? Armar un partido de fútbol entre amigos nunca fue tan fácil"
			}, function( response ) {
				// do nothing
			} );
	    };
	    $scope.shareTW = function(){
	    	//docs: https://dev.twitter.com/web/intents
	    	var url = "https://twitter.com/intent/tweet?text=Copate a este doparti!&url=http%3A%2F%2Fwww.futzapp.com?token=" + $scope.match.token;
	    	var opts = 'status=1';
	    
	    	window.open(url, 'twitter', opts);
	    };
}]);

fulboControllers.controller('GroupsController', ['$location', '$rootScope', '$scope', 'Groups', 'Users',
	function($location, $rootScope, $scope, Groups, Users) {
		$rootScope.activePage = "groups";
		
		$scope.openGroup = function(groupId){
			$location.path( "group/" + groupId );
		};
		
		$scope.groups = Users.getGroups({id: $rootScope.user.id});
		
		$scope.newGroup = function(){
			var name = $("#newGroupName").val();
	    	var admin_userId = $rootScope.user.id;
			
	    	if(name == ""){
	    		showAlert("Error", "Debe ingresar un nombre para el grupo.");
	    		return false;
	    	}
	    	
			var group = {
		        name: name,
		        image: "",
		        admin_userId: admin_userId
			};
		    	
			Groups.save(group, function(newGroup){
		    	console.log("Group saved, id:" + newGroup.id);
		    	$scope.groups = Users.getGroups({id: $rootScope.user.id});
		    }, function(){
		    	console.log("Failed saving group!");
		    	showAlert("Error", "Hubo un error al crear el partido! Intente nuevamente.");
		    });
			
	    	$('#newGroupModal').modal('hide');
		};
	}]);

fulboControllers.controller('GroupController', ['$rootScope', '$scope', '$routeParams', 'Groups', 'Facebook',
 function($rootScope, $scope, $routeParams, Groups, Facebook) {
	$rootScope.activePage = "group";
	
	$scope.imageUploaded = false;
	
	$scope.group = Groups.getUsers({id: $routeParams.groupId});
		
	$scope.friendsSelected = [];
	Facebook.getFriends(function(response) {
		$scope.friends = response;
	});
	
	$scope.selectFriend = function(friend){
		if(friend.selected == undefined || !friend.selected){
			friend.selected = true;
			$scope.friendsSelected.push(friend);
		} else {
			friend.selected = false;
			for(var i = 0; i < $scope.friendsSelected.length; i++) {
                if($scope.friendsSelected[i].name === friend.name) {
                	$scope.friendsSelected.splice(i, 1);
                	break;
                }
            }
		}
	};
	
	$scope.isSelected = function(obj) {
        return obj.selected;
    };
    
    $scope.imagePath = "";
    $scope.resetImage = function(param) {
    	$scope.imagePath = "";
    	$scope.imageUploaded = false;
    };
    $scope.fileAdded = function(param) {
    	$scope.imageUploaded = true;
    	$scope.imagePath = "/images/groups/" + param.name;
    	console.log("File Added!");
	};
    $scope.saveImage = function() {
    	if($scope.imageUploaded){
    		$scope.group.image = $scope.imagePath;
    		$scope.update();
    		$('#groupImageModal').modal('hide');
    	} else 
    		showAlert("Error", "No se pudo subir la imagen. Intente nuevamente.");
    };
    
    $scope.update = function() {
    	Groups.update($scope.group, function(){
			console.log("group updated!");
		}, function(){
			console.log("group update failed!");
		});
    };
    
    $scope.addUsers = function() {
    	var data = {
    		userIds: [],
    		groupId: $scope.group.id
    	};
    	
    	//add existing members
    	for(var i = 0; i < $scope.group.users.length; i++){
    		data.userIds.push($scope.group.users[i].fbId.toString());
    	}
    	
    	//add new members
    	for(var i = 0; i < $scope.friendsSelected.length; i++){
    		data.userIds.push($scope.friendsSelected[i].id.toString());
    	}
    	
    	Groups.updateUsers(data, function(response){
    		$scope.group = response;
    		$('#newUserGroupModal').modal('hide');
    	});
    };
}]);

fulboControllers.controller('ProfileController', ['$rootScope', '$scope', 'UsersAuth', 'Users', 
  function($rootScope, $scope, UsersAuth, Users) {
	$rootScope.activePage = "profile";
	
	//TODO: calculate games played
	$scope.gamesPlayed = 0;
	
	$scope.saveUserData = function() {
		Users.update($rootScope.user, function(){
			console.log("user updated!");
		}, function(){
			console.log("user update failed!");
		});
	};
	
	$scope.logout = function() {
    	UsersAuth.logout();
    };
}]);

